package gemini.pollux.ui.client.page;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 * This class contains all of the UI components of Root screen.
 * 
 * @author fhe
 * 
 */
public class RootView extends Composite implements RootPresenter.Display {

	@UiField
	DecoratorPanel pnlContent;

	@UiField
	VerticalPanel pnlNavigation;

	private List<Widget> navigationWidgets;

	@UiTemplate("RootView.ui.xml")
	interface MyUiBinder extends UiBinder<Panel, RootView> {
	}

	private static final MyUiBinder binder = GWT.create(MyUiBinder.class);

	public RootView() {
		initWidget(binder.createAndBindUi(this));
	}

	@Override
	public void changeContent(final Widget w) {
		pnlContent.clear();
		pnlContent.add(w);
	}

	@Override
    public void setNavigationAtIndex(final Widget w, int idx, boolean replace) {
    		setWidgetToList(getNavigationWidgets(), w, idx, replace);
    		setWidgetsToNavigation();
    }

	private void setWidgetsToNavigation() {
		pnlNavigation.clear();
		for (Widget widget : navigationWidgets) {
			pnlNavigation.add(widget);
		}
	}
	
	public List<Widget> getNavigationWidgets() {
		if (navigationWidgets == null) {
			navigationWidgets = new ArrayList<Widget>();
		}
		return navigationWidgets;
	}
	
	private void setWidgetToList(List<Widget> list, Widget w, int idx, boolean isReplace) {
		if(list.size() == 0){
			list.add(w);
		} else {
			if (isReplace) {
				if (idx >= list.size()) {
					idx = list.size() - 1;
				}
				
				if (list.get(idx) != null) {
					list.get(idx).removeFromParent();
					list.remove(idx);
				}
				
				if (w != null) {
					list.add(idx, w);
				}
			} else {
				if (idx == -1) {
					list.clear();
					list.add(w);
				} else if (idx >= list.size()) {
					list.add(w);
				} else {
					list.add(idx, w);
				}
			}
		}
	}

	@Override
	public Widget asWidget() {
		return this;
	}

	@Override
	public int getNavigationCount() {
		return pnlNavigation.getWidgetCount();
	}

	@Override
	public void visibleContent(boolean visible) {
		pnlContent.setVisible(visible);
	}
	
	@Override
	public void visibleNavigation(boolean visible) {
		pnlNavigation.setVisible(visible);
	}
}